import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
import { PERM_KEY } from '../decorator/require-perm.decorator';

@Injectable()
export class PermGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}
  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const req = context.switchToHttp().getRequest();
    const requirePerm = this.reflector.getAllAndOverride(PERM_KEY, [context.getClass(), context.getHandler()]);
    if (requirePerm) {
      return this.hasPerm(
        requirePerm,
        req.user.perms.map((perm) => perm.permName),
      );
    }
    return true;
  }

  hasPerm(perm: string, perms: string[]) {
    const AllPerm = '*:*:*';
    return perms.includes(AllPerm) || perms.some((v) => v === perm);
  }
}
